import express from 'express';
import sql from '../../sql.js';
const router = express.Router();

// 查询评论接口
router.post('/searchComment', async (req, res) => {
    const articleId = req.body.articleId;
    const diaryId = req.body.diaryId;
    const userId = req.body.userId;
    const isRead = req.body.isRead;
    let page = parseInt(req.body.page) || 1;
    const pageSize = parseInt(req.body.pageSize) || 10;
    let comments;
    try {
        // 构建查询语句
        let query = 'SELECT * FROM comment';
        let whereClauses = [];
        let values = [];

        if (articleId!== undefined) {
            whereClauses.push('article_id =?');
            values.push(articleId);
        }
        if (diaryId!== undefined) {
            whereClauses.push('diary_id =?');
            values.push(diaryId);
        }
        if (userId!== undefined) {
            whereClauses.push('user_id =?');
            values.push(userId);
        }
        if (isRead!== undefined) {
            whereClauses.push('is_read =?');
            values.push(isRead);
        }

        if (whereClauses.length > 0) {
            query += ' WHERE ' + whereClauses.join(' AND ');
        }

        // 分页
        query += ` LIMIT ?, ?`;
        let offset = (page - 1) * pageSize;
        values.push(offset, pageSize);
        [comments] = await sql.query(query, values);
        if (comments.length === 0 && page > 1) {
           page = page - 1
           offset = (page - 1) * pageSize;
           values[values.length - 2] = offset;
           const [data] = await sql.query(query, values);
           comments = data;
        }

        // 计算总数
        const countQuery = `SELECT COUNT(*) AS total FROM comment ${whereClauses.length > 0? ' WHERE ' + whereClauses.join(' AND ') : ''}`;
        const [countResult] = await sql.query(countQuery, values);
        const totalCount = countResult[0].total;
        const totalPages = Math.ceil(totalCount / pageSize);

        const noReadQuery = 'SELECT COUNT(*) AS noReadCount FROM comment WHERE is_read = 0';
        const [noReadResult] = await sql.query(noReadQuery);
        const noRead = noReadResult[0].noReadCount;

        res.send({
            status: 'success',
            message: '评论查询成功',
            data: comments,
            pagination: {
                currentPage: page,
                pageSize: pageSize,
                totalCount: totalCount,
                totalPages: totalPages
            },
            noRead: noRead
        });
    } catch (error) {
        console.error('查询评论错误：', error);
        res.send({
            status: 'error',
            message: '服务器内部错误',
            errorCode: 500
        });
    }
});

// 更新评论状态接口
router.put('/updateCommentReadStatus/:commentId', async (req, res) => {
    const commentId = req.params.commentId;
    try {
        const query = 'UPDATE comment SET is_read = 1 WHERE ID =?';
        await sql.query(query, [commentId]);
        res.send({
            status: 'success',
            message: '评论状态更新成功'
        });
    } catch (error) {
        console.error('更新私信状态错误：', error);
        res.send({
            status: 'error',
            message: '服务器内部错误',
            errorCode: 500
        });
    }
  });

 // 删除评论接口
router.delete('/deleteComment/:commentId', async (req, res) => {
  const commentId = req.params.commentId;
  try {
      const query = 'DELETE FROM comment WHERE ID =?';
      await sql.query(query, [commentId]);
      res.send({
          status: 'success',
          message: '评论删除成功'
      });
  } catch (error) {
      console.error('删除评论错误：', error);
      res.send({
          status: 'error',
          message: '服务器内部错误',
          errorCode: 500
      });
  }
});

export default router;








